package com.easyattendance.services;

import java.util.Iterator;
import java.util.List;



import java.util.Properties;

import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;

import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;

import com.easyattendance.model.AttendanceTakenBy;
import com.easyattendance.model.EmailSettings;
import com.easyattendance.model.Parent;
import com.easyattendance.model.Student;
import com.easyattendance.model.StudentAttendance;
import com.easyattendance.util.HibernateUtil;

public class AttendanceSubmissionService {
	
	/* Method to CREATE attendance records in the database */
	   public synchronized boolean saveAttendance(StudentAttendance attendance){

		  Session session = HibernateUtil.openSession();
	      Transaction tx = null;
	      boolean result=false;
	      
	      try{
	         tx = session.beginTransaction();	         
	         
	        	 session.save(attendance);
	           	 tx.commit();
	          
	         result=true;
	          
	      }catch (HibernateException e) {
	         if (tx!=null) tx.rollback();
	         e.printStackTrace(); 
	      }finally {
	         session.close(); 
	      }
	      return result;
	   }
	   
	   public synchronized boolean saveAttendanceTakenBy(AttendanceTakenBy attendancedetail){

			  Session session = HibernateUtil.openSession();
		      Transaction tx = null;
		      boolean result=false;
		      
		      try{
		         tx = session.beginTransaction();
		         
		         
		        	 session.save(attendancedetail);
		           	 tx.commit();
		          
		         result=true;
		          
		      }catch (HibernateException e) {
		         if (tx!=null) tx.rollback();
		         e.printStackTrace(); 
		      }finally {
		         session.close(); 
		      }
		      return result;
		   }
		   
	   
	public boolean ifAlreadyExists(StudentAttendance newStudentAttendance) {
		boolean flag = false;

		Session session = HibernateUtil.openSession();
		Transaction tx = null;
		List attendances = null;
		try {
			tx = session.beginTransaction();
			attendances = session.createQuery("FROM StudentAttendance").list();
			for (Iterator iterator = attendances.iterator(); iterator.hasNext();) {
				StudentAttendance attendance = (StudentAttendance) iterator.next();
				if (attendance.equals(newStudentAttendance)) {
					System.out.println("This day's attendance already exists");
					flag = true;
					break;
				}

			}
			tx.commit();
		} catch (HibernateException e) {
			if (tx != null)
				tx.rollback();
			e.printStackTrace();
		} finally {
			session.close();
		}

		return flag;

	}
	   
	public boolean ifDetailsAlreadyExists(AttendanceTakenBy newAttendanceDetail) {
		boolean flag = false;

		Session session = HibernateUtil.openSession();
		Transaction tx = null;
		List attendances = null;
		try {
			tx = session.beginTransaction();
			attendances = session.createQuery("FROM AttendanceTakenBy").list();
			for (Iterator iterator = attendances.iterator(); iterator.hasNext();) {
				AttendanceTakenBy attendance = (AttendanceTakenBy) iterator.next();
				if (attendance.equals(newAttendanceDetail)) {
					System.out.println("This day's attendance details already exists");
					flag = true;
					break;
				}

			}
			tx.commit();
		} catch (HibernateException e) {
			if (tx != null)
				tx.rollback();
			e.printStackTrace();
		} finally {
			session.close();
		}

		return flag;

	}
		/* Method to  READ all the Attendance values */
		   public List listAttendance( ) {
			   Session session = HibernateUtil.openSession();
		      Transaction tx = null;
		      List attendances = null;
		      try{
		         tx = session.beginTransaction();
		         attendances = session.createQuery("FROM StudentAttendance").list(); 
		         for (Iterator iterator = attendances.iterator(); iterator.hasNext();){
		        	 StudentAttendance attendance = (StudentAttendance) iterator.next(); 
		             
		         }
		         tx.commit();
		      }catch (HibernateException e) {
		         if (tx!=null) tx.rollback();
		         e.printStackTrace(); 
		      }finally {
		         session.close(); 
		      }
		      return attendances;
		   }
		   
		   public EmailSettings getEmailSettingsBySectionEmailId(String emailId)
			{
				 Session session = HibernateUtil.openSession();
			      Transaction tx = null;
			      EmailSettings mailSetting = null;
			      Query query;
			      
			      try{
				         tx = session.beginTransaction();
				         query = session.createQuery("FROM EmailSettings where send_email_id='"+emailId+"'");
				         mailSetting=(EmailSettings) query.uniqueResult();
			      }
			      catch (HibernateException e) {
				         if (tx!=null) tx.rollback();
				         e.printStackTrace(); 
				      }finally {
				         session.close(); 
				      }
			      
				return mailSetting;
			}
			
			public Parent getParentByStudentId(String stud_rollno,String class_id)
			{
				 Session session = HibernateUtil.openSession();
			      Transaction tx = null;
			      Student student = null;
			      Query query;
			      
			      try{
				         tx = session.beginTransaction();
				         query = session.createQuery("FROM Student where stud_roll_no="+stud_rollno+" and class_id='"+class_id+"'");
				         student= (Student) query.uniqueResult();
			      }
			      catch (HibernateException e) {
				         if (tx!=null) tx.rollback();
				         e.printStackTrace(); 
				      }finally {
				         session.close(); 
				      }
			      
				return student.getParent();
			}
			
			public boolean SendMail(String from_mailId,String pwd,String msg,Parent parent)
			{
				boolean IsMailSent=false;
				 	final String username = from_mailId;
					final String password = pwd;
			 
					Properties props = new Properties();
					props.put("mail.smtp.auth", "true");
					props.put("mail.smtp.starttls.enable", "true");
					props.put("mail.smtp.host", "smtp.gmail.com");
					props.put("mail.smtp.port", "587");
			 
					javax.mail.Session session = javax.mail.Session.getInstance(props,
					  new javax.mail.Authenticator() {
						protected PasswordAuthentication getPasswordAuthentication() {
							return new PasswordAuthentication(username, password);
						}
					  });
			 
					try {
			 
						Message message = new MimeMessage(session);
					
						message.setFrom(new InternetAddress(username));
						message.setRecipients(Message.RecipientType.TO,
						InternetAddress.parse(parent.getParent_email_id())); // parentEmailId should be passed here afterwards
						/* message.setRecipients(Message.RecipientType.TO,
							InternetAddress.parse(teacherEmailId)); */
						message.setSubject("To inform about your ward's absence in school");

						String msg_text="Dear, "+parent.getParent_name()
								+ "\n"+msg;
						
								// Create the message part 
								MimeBodyPart messageBodyPart = new MimeBodyPart();

								// Fill the message
								messageBodyPart.setContent(msg_text,"text/html");

								MimeMultipart multipart = new MimeMultipart();
								multipart.addBodyPart(messageBodyPart);

								// Put parts in message
								message.setContent(multipart);
								message.setText(msg_text);
							Transport.send(message);
			 
						System.out.println("Mail sent!!");
			 
					} catch (MessagingException e) {
						throw new RuntimeException(e);
					} 
				return IsMailSent;
			}

	   

}
